<template>
  <div>
    <headerTop title="学生管理">
      <el-button @click="exportAll">批量添加</el-button>
      <el-button type="primary" @click="student">添加学生</el-button>
    </headerTop>

    <!-- 查询内容 -->
    <el-form style="display: flex" :model="query" label-width="60px">
      <el-form-item label="关键字">
        <el-input v-model="query.key" placeholder="请输入关键字" />
      </el-form-item>

      <el-form-item label="部门">
        <el-cascader
          v-model="query.depid"
          :options="options"
          :props="{ value: 'id', label: 'name' }"
          placeholder="请输入部门"
        />
      </el-form-item>

      <el-form-item label="班级">
        <el-select
          v-model="query.classid"
          class="characters"
          placeholder="请选择班级"
        >
          <el-option 
              v-for="(item, index) in classoption"
              :key="index"
              :label="item.name"
              :value="item.name" />
        </el-select>
      </el-form-item>
      <el-button style="margin-left: 20px" type="primary" @click="Submit"
        >搜索</el-button
      >
      <el-button type="danger" @click="batchdel">批量删除</el-button>
    </el-form>

    <!-- 列表 -->
    <tableAdmin
      :tableHead="tableHead"
      :tableData="tableData"
      @pass="pass"
      @edit="edit"
      @del="del"
      @tableSelected="tableSelected"
    ></tableAdmin>

    <!-- 分页 -->
    <pages
      :total="total"
      :page="query.page"
      :pageSize="query.psize"
      @changePageSize="changePageSize"
      @changePage="changePage"
    />

    <!-- 添加修改 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isText === true ? '添加学生' : '修改学生'"
      width="45%"
      :modal="false"
    >
    <studentDialog :isText='isText' :idsAamin='idsAamin' @clickChild=clickChild @click="click" />
  </el-dialog>

  <!-- 重置密码的弹框 -->
  <el-dialog v-model="dialogPass" title="重置密码" width="40%">
      <div>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="姓名" prop="username">
            <el-input v-model="ruleForm.username" disabled class="input" />
          </el-form-item>

          <el-form-item label="新密码" prop="pass">
            <el-input
              v-model="ruleForm.pass"
              type="password"
              show-password
              class="input"
            />
          </el-form-item>

          <el-form-item label="确认密码" prop="password">
            <el-input
              v-model="ruleForm.password"
              type="password"
              show-password
              class="input"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogPass = false">取消</el-button>
          <el-button type="primary" @click="delPass"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量添加的弹框 -->
    <textDialog v-show="dialogStore.show" width="40%">
      <template #content>
        <!-- 上传文件  -->
        <clickUpload @uploadData="getUploadData"></clickUpload>
      </template>
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" size="default" @click="handleData">确定</el-button>
      </template>
    </textDialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref,toRefs } from 'vue';
import {departmentList,classesList,studentList,studentDel,studentDelall,studentAdd} from '../../api/student';
import tableAdmin from '../../components/table/tableAdmin.vue';
import pages from '../../components/pages/pages.vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import studentDialog from './studentDialog.vue'
import type { FormInstance, FormRules } from 'element-plus';
import headerTop from '../../components/header/headerTop.vue'
import textDialog from "../../components/textAdmin/textDialog.vue"
import { useDialogStore } from '../../store/dialog';
import clickUpload from '../../components/textAdmin/clickUpload.vue'

const dialogStore = useDialogStore()
const { show, title } = toRefs(dialogStore)
const dialogPass = ref(false);
const dialogVisible = ref(false);
const isText = ref(false); //添加修改的标题
const form = reactive({
  name: '',
  value: '',
});

const formSize = ref('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  id: 0,
  name:'',
  username: '',
  pass: '',
  password: '',
});

const rules = reactive<FormRules>({
  pass: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  password: [{ required: true, message: '请再次输入密码', trigger: 'blur' }],
});

// 获取部门列表
const options = ref([]);
const optionsList = async () => {
  let data = {
    page: 1,
    psize: 5,
  };
  const res = await departmentList(data);
  console.log(res);
  options.value = res.data.list;
};
optionsList();

// 班级列表
const classoption = ref([] as any[]);
const classList = async () => {
  let query = {
    page: 1,
    psize: 5,
  };
  const res = await classesList(query);
  console.log(res);
  classoption.value = res.data.list;
};
classList();

//列表数据
const tableData = ref([]);
const tableHead: any[] = [
  {
    label: '学生姓名',
    prop: 'name',
  },
  {
    label: '备注',
    prop: 'remarks',
  },
  {
    label: '所属部门',
    prop: 'depname',
  },
  {
    label: '所在班级',
    prop: 'classname',
  },
  {
    label: '账号',
    prop: 'pass',
  },
  {
    label: '添加时间',
    prop: 'addtime',
  },
  {
    label: '操作',
    type: 'button',
    buttons: [
      {
        text: '重置密码',
        event: 'pass',
        type: 'primary',
        show: true,
      },
      {
        text: '修改',
        event: 'edit',
        type: 'primary',
        show: true,
      },
      {
        text: '删除',
        event: 'del',
        type: 'primary',
        show: true,
      },
    ],
  },
];
let total = ref(0); // 总条数
const query = reactive({
  page: 1,
  psize: 10,
  key: '',
  depid: '',
  classid:''
});
const getList = async () => {
  const res = await studentList(query);
  console.log(123123123, res);
  tableData.value = res.data.list;
  total.value = res.data.counts;
};
getList();

// 切换分页数据
const changePageSize = (val: number) => {
  console.log('val-pageSize', val);
  query.psize = val; //页码
  // 请求列表数据...
  getList();
};

const changePage = (val: number) => {
  console.log('val-page', val);
  query.page = val; //每页显示多少条
  // 请求列表数据...
  getList();
};

// 查询
const Submit = () => {
  getList();
};

// 重置密码
const pass = (row: any) => {
  // console.log('密码',row);
  let { name, id } = row;
  console.log(name);
  console.log(id);
  dialogPass.value = true;
  ruleForm.id = id;
  ruleForm.username = name;
};

// 点击确定重置密码
const delPass = async () => {
  if (ruleForm.pass !== ruleForm.password) {
    ElMessage({
      message: '请确定密码保持一致！',
      type: 'warning',
    });
    return;
  }
  const res:any = await studentAdd(ruleForm);
  console.log(res);
  if (res.errCode === 10000) {
    ElMessage({
      type: 'success',
      message: '修改成功',
    });
    ruleForm.pass=''
    ruleForm.password=''
    dialogPass.value = false;
  }
};

// 删除
const del = (ids: any) => {
  let { id } = ids;
  console.log(id);
  ElMessageBox.confirm(
    '确定要删除所选项吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res:any = await studentDel({ id: id });
      console.log(res);
      if (res.errCode === 10000) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        getList();
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

// 赋值批量删除的id
const ids = ref([])
// 获取到批量删除的id
const tableSelected = (val: any) => {
  // console.log(val);
  ids.value = val.map((item:any)=> item.id)
  console.log(ids.value);
};

// 批量删除
const batchdel = ()=>{
  console.log(ids.value);
  if(ids.value.length){
    ElMessageBox.confirm(
    '确定要删除所选项吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res:any = await studentDelall({ ids: ids.value });
      console.log(res);
      if (res.errCode === 10000) {
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        getList();
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
  }else{
    ElMessage.error('请选中要删除的选项');
  }
}

// 添加修改的id
const idsAamin = ref(0)
// 点击取消按钮关闭弹窗
const clickChild = (row:boolean)=>{
  dialogVisible.value=row
}

// 修改
const edit = (row:any) => {
  Object.assign(idsAamin,row)//Object.assign ()对象是用于将所有可枚举属性的值从一个或多个源对象复制到目标对象，将返回目标对象。
  console.log(row);
  let {id} = row
  console.log(id);
  idsAamin.value=row
  isText.value=false
  dialogVisible.value=true
};

// 添加修改点击关闭弹窗
const click = (row:boolean)=>{
  dialogVisible.value=row
  getList();
}

// 点击添加按钮出弹窗
const student = ()=>{
  dialogVisible.value=true
  isText.value=true
}

// 批量添加
const exportAll =()=>{
  dialogStore.$patch(state=>{
    state.show=true
    state.title='批量上传学生信息'
  })
}
// const imports = (e:any)=>{
  // params.value.questions = e

// 取消导入
const cancel = () => {
  dialogStore.$patch(state => {
    state.show = false
    state.title = ''
  })
}

let list = ref([])
// 上传文件返回的数据
const getUploadData = (data: any) => {
  list.value = data
}

const handleData = async () => {
  // 先判断导入的数据
  let len = list.value.length
  if (!len) {
    ElMessage.error('请上传文件')
    return
  }
  // 处理数据
  // let promiseArr:any = []
  for (let i = 0; i < len; i++) {
    const promise = await studentAdd(list.value[i])
    console.log(promise);
    if (promise.errCode===10000) {
      ElMessage.success('上传成功')
      // promiseArr.push(promise.errCode)
      dialogStore.$patch(state => {
        state.show = false
        state.title = ''
      })
      getList();
    } else {
      ElMessage.error('上传失败')
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 200px;
}
.input {
  width: 280px;
}
</style>
